package com.xoa.service.party;


import com.xoa.dao.party.MapOwnerinfoMapper;
import com.xoa.dao.party.OrgDepartmentMapper;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.party.OrgDepartment;
import com.xoa.model.party.OrgDepartmentWithBLOBs;
import com.xoa.model.party.OrgInfo;
import com.xoa.model.users.Users;
import com.xoa.service.users.UsersService;
import com.xoa.util.Constant;
import com.xoa.util.CookiesUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.dataSource.ContextHolder;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.UUID;
import com.xoa.dao.party.OrgPartyMemberMapper;
@Service
public class OrgDepartmentService {
    @Autowired
    private OrgPartyMemberMapper orgPartyMemberMapper;
    @Autowired
    private OrgDepartmentMapper orgDepartmentMapper;
    @Resource
    private MapOwnerinfoMapper mapOwnerinfoMapper;

    @Resource
    private UsersService usersService;
    public BaseWrapper addOrgDepartment(OrgDepartmentWithBLOBs orgDepartment) {
        BaseWrapper baseWrapper = new BaseWrapper();
        baseWrapper.setStatus(true);
        if (StringUtils.checkNull(orgDepartment.getOrgDeptName())) {
            baseWrapper.setMsg("参数错误");
            baseWrapper.setFlag(true);
        }
        int total = orgDepartmentMapper.insertSelective(orgDepartment);
        if (total > 0) {
            baseWrapper.setMsg("添加成功");
            baseWrapper.setFlag(true);
            baseWrapper.setData(orgDepartment);
        } else {
            baseWrapper.setMsg("参数错误");
            baseWrapper.setFlag(false);
        }
        return baseWrapper;
    }

    public ToJson<OrgDepartmentWithBLOBs> queryByDepIdList(Integer depId) {
        BaseWrappers baseWrapper = new BaseWrappers();
        baseWrapper.setStatus(true);
        ToJson<OrgDepartmentWithBLOBs> toJson = new ToJson<>();
        List<OrgDepartmentWithBLOBs> departmentWithBLOBsList = orgDepartmentMapper.queryByDepIdList(depId);
        for (OrgDepartmentWithBLOBs departmentWithBLOBs : departmentWithBLOBsList) {
            if(departmentWithBLOBs.getOrgDeptId()==null && departmentWithBLOBs.getOrgDeptName()==null){
                continue;
            }
            departmentWithBLOBs.setDeptId(String.valueOf(departmentWithBLOBs.getOrgDeptId()));
            departmentWithBLOBs.setDeptName(departmentWithBLOBs.getOrgDeptName());
        }
        toJson.setObj(departmentWithBLOBsList);
        toJson.setFlag(0);
        return toJson;
    }


    public BaseWrapper queryByIdOrgDepartmentWithBLOBs(HttpServletRequest request, Integer depId) {
        String sqlType = "xoa"
                + (String) request.getSession().getAttribute("loginDateSouse");
        BaseWrapper baseWrapper = new BaseWrapper();
        baseWrapper.setStatus(true);
        if(depId==1){
            OrgDepartmentWithBLOBs orgDepartmentWithBLOBs = orgDepartmentMapper.selectByPrimaryKeyById(depId);

            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if (orgDepartmentWithBLOBs != null) {
                 orgDepartmentWithBLOBs.setCountUser(orgPartyMemberMapper.countOrgParty(orgDepartmentWithBLOBs.getOrgDeptId()));
                if (orgDepartmentWithBLOBs.getAttachmentId() != null && orgDepartmentWithBLOBs.getAttachmentName() != null) {
                    attachmentList= GetAttachmentListUtil.returnAttachment( orgDepartmentWithBLOBs.getAttachmentName(),orgDepartmentWithBLOBs.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.MODULE_photo);
                }
                orgDepartmentWithBLOBs.setAttachmentList(attachmentList);
            }
            baseWrapper.setData(orgDepartmentWithBLOBs);
        }else {
            OrgDepartmentWithBLOBs orgDepartmentWithBLOBs = orgDepartmentMapper.selectByPrimaryKeyById(depId);
            //附件处理（遍历时）
            List<Attachment> attachmentList=new ArrayList<Attachment>();

            if (orgDepartmentWithBLOBs != null) {
                orgDepartmentWithBLOBs.setCountUser(orgPartyMemberMapper.countOrgParty(orgDepartmentWithBLOBs.getOrgDeptId()));
                if (orgDepartmentWithBLOBs.getAttachmentId() != null && orgDepartmentWithBLOBs.getAttachmentName() != null) {
                    attachmentList= GetAttachmentListUtil.returnAttachment( orgDepartmentWithBLOBs.getAttachmentName(),orgDepartmentWithBLOBs.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.MODULE_photo);
                }
                orgDepartmentWithBLOBs.setAttachmentList(attachmentList);
            }

            OrgDepartmentWithBLOBs orgDepartmentWithBLOBs1rgDepartmentWithBLOBs =orgDepartmentMapper.selectByPrimaryKeyById(orgDepartmentWithBLOBs.getOrgDeptParent());
            if(orgDepartmentWithBLOBs1rgDepartmentWithBLOBs!=null) {
                orgDepartmentWithBLOBs.setOrgDeptParentName(orgDepartmentWithBLOBs1rgDepartmentWithBLOBs.getOrgDeptName());
            }

            baseWrapper.setData(orgDepartmentWithBLOBs);
        }
        return baseWrapper;
    }


    public ToJson<OrgDepartmentWithBLOBs> queryDepIdList(OrgDepartment orgDepartment) {
        BaseWrappers baseWrapper = new BaseWrappers();
        baseWrapper.setStatus(true);
        ToJson<OrgDepartmentWithBLOBs> toJson = new ToJson<>();
        List<OrgDepartmentWithBLOBs> departmentWithBLOBsList = orgDepartmentMapper.queryDepIdList(orgDepartment);
        for (OrgDepartmentWithBLOBs departmentWithBLOBs : departmentWithBLOBsList) {
            departmentWithBLOBs.setDeptId(String.valueOf(departmentWithBLOBs.getOrgDeptId()));
            departmentWithBLOBs.setDeptName(departmentWithBLOBs.getOrgDeptName());
        }
        toJson.setObj(departmentWithBLOBsList);
        toJson.setFlag(0);
        return toJson;
    }

    public BaseWrapper updateOrgDepartment(OrgDepartmentWithBLOBs orgDepartment) {
        BaseWrapper baseWrapper = new BaseWrapper();
        baseWrapper.setStatus(true);
        if (StringUtils.checkNull(orgDepartment.getOrgDeptName())) {
            baseWrapper.setMsg("参数错误");
            baseWrapper.setFlag(true);
        }
        int total = orgDepartmentMapper.updateOrgDepartment(orgDepartment);
        if (total > 0) {
            baseWrapper.setMsg("修改成功");
            baseWrapper.setFlag(true);
            baseWrapper.setData(orgDepartment);
        } else {
            baseWrapper.setMsg("参数错误");
            baseWrapper.setFlag(false);
        }
        return baseWrapper;
    }

    public ToJson selectSum(){
        ToJson json=new ToJson();
        List<OrgDepartment> list=orgDepartmentMapper.selectSum();
        //List<OrgDepartment> list=orgDepartmentMapper.queryDepIdListGroup();
        try{
            json.setObj(list);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            json.setMsg("err");
            json.setFlag(1);
            e.printStackTrace();
        }finally {
            return  json;
        }
    }
    public ToJson selectSumGroup(){
        ToJson json=new ToJson();
        List<OrgDepartment> list=orgDepartmentMapper.selectSumGroup();
        //List<OrgDepartment> list=orgDepartmentMapper.queryDepIdListGroup();
        try{
            json.setObj(list);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            json.setMsg("err");
            json.setFlag(1);
            e.printStackTrace();
        }finally {
            return  json;
        }
    }


    public ToJson oudInsert(MultipartFile file){
             ToJson json=new ToJson();
             return json;
    }

    public ToJson ecoudInsert(MultipartFile file){
        int count=0;//計數器
        ToJson json=new ToJson();
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            }else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");//判读当前系统
                    //读取配置文件
                    ResourceBundle rb = ResourceBundle.getBundle("upload");
                    String osName = System.getProperty("os.name");
                    StringBuffer path = new StringBuffer();
                    if (osName.toLowerCase().startsWith("win")) {
                        path = path.append(rb.getString("upload.win"));
                    } else {
                        path = path.append(rb.getString("upload.linux"));
                    }
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
//                    file.transferTo(dest);
//                    // 将文件上传成功后进行读取文件
//                    // 进行读取的路径
//                    String readPath = path.append(newFileName).toString();
//                    InputStream in = new FileInputStream(readPath);
                    InputStream in =  file.getInputStream();
//                  得到所在位置

                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    //得到Id
                    List<OrgDepartment> deptList=orgDepartmentMapper.selectByOrgDepartment();
                    for (int i = 1; i <= lastRowNum; i++) {
                        OrgDepartmentWithBLOBs orgDepartmentWithBLOBs = new OrgDepartmentWithBLOBs();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //排序号
                                            if(cell.getCellType() == CellType.STRING){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            orgDepartmentWithBLOBs.setOrgDeptNo(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 1:
                                            //党组织名称
                                            if(cell.getCellType() == CellType.STRING.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            orgDepartmentWithBLOBs.setOrgDeptName(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //上级组织
                                            if(cell.getCellType() == CellType.STRING.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            //得到上级组织id通过名字
                                            if(cell.getStringCellValue()!=null &&!"".equals(cell.getStringCellValue())){
                                                for(OrgDepartment orgDepartment1:deptList){
                                                    if(orgDepartment1.getDeptName().equals(cell.getStringCellValue())){
                                                        orgDepartmentWithBLOBs.setOrgDeptParent(orgDepartment1.getOrgDeptId());
                                                    }
                                                } ;
                                            }else{
                                                orgDepartmentWithBLOBs.setOrgDeptParent(0);
                                            }
                                            break;
                                        case 3:
                                            //支部书记（组织管理园）
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }

                                            orgDepartmentWithBLOBs.setOrgOrgAdmin(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //电话
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }

                                            orgDepartmentWithBLOBs.setOrgTelNo(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 5:
                                            //地址
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }

                                            orgDepartmentWithBLOBs.setOrgDeptAddress(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            //地址坐标
                                            String addresslocation="";
                                            if(cell.getStringCellValue()!=null&&!"".equals(cell.getStringCellValue())){
                                                addresslocation = mapOwnerinfoMapper.selectCoordingbyName(cell.getStringCellValue());
                                            }
                                            orgDepartmentWithBLOBs.setGridLocation(addresslocation);
                                            break;
                                        case 6:
                                            //电话
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            orgDepartmentWithBLOBs.setOrgDeptFunc(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        default:
                                            json.setFlag(0);
                                            json.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            //将数据放入数据库
                            int count1=orgDepartmentMapper.insertSelective(orgDepartmentWithBLOBs);
                            if(count1>0) {
                                count += count1;
                            }
                            dest.delete();
                        }
                    }

                }
            }
            if(count>0){
                json.setTotleNum(count);
                json.setMsg("ok");
                json.setFlag(0);
                return  json;
            }
        }catch (Exception e){
            json.setMsg("err");
            e.printStackTrace();
        }finally {
            return json;
        }
    }
    //通过地址查询党支部信息
    public ToJson selectbylocation(String location){
      ToJson toJson=new ToJson();
      try{
          List<OrgInfo> list=orgDepartmentMapper.selectbylocation(location);
          toJson.setObj(list);
          toJson.setMsg("ok");
          toJson.setFlag(0);
      }catch(Exception e){
          toJson.setMsg("error");
          toJson.setFlag(1);
          e.getMessage();
      }
        return toJson;
    }

    public ToJson selectbyLocationOrgDepart(String location){
        ToJson toJson=new ToJson();
        try{
//            //得到所有地图查询到的地址串
//            List<String> maplist=mapOwnerinfoMapper.selectCoordingbyNamelike(location);
//           //得到所有党组织
            List<OrgDepartmentWithBLOBs> orglist=orgDepartmentMapper.queryDepIdList(new OrgDepartment());
            //返回有坐标的党组织
            List<OrgDepartment> retlist=new ArrayList<>();
           if(orglist!=null&&orglist.size()>0){
               for(OrgDepartment s:orglist){
                   if(s.getOrgDeptName().contains(location)){
                       retlist.add(s);
                   }
               }
           }
           toJson.setMsg("ok");
           toJson.setFlag(0);
           toJson.setObj(retlist);
        }catch (Exception e){
            e.getMessage();
            toJson.setFlag(1);
            toJson.setMsg("error");
        }
        return toJson;
    }

    public ToJson<OrgDepartment> delDepartment(Integer orgDeptId, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        ToJson<OrgDepartment> json = new ToJson<OrgDepartment>(0, null);
        try {
//            Department dep = departmentService.getDeptById(department.getDeptId());
            OrgDepartment department = orgDepartmentMapper.getDeptById(orgDeptId);
            department.setOrgDeptParentName(orgDepartmentMapper.getDeptNameByDeptId(department.getOrgDeptParent()));



//            List<OrgDepartment> list = departmentService.getChDeptByNo(dep.getDeptNo());
            List<OrgDepartment> list = orgDepartmentMapper.getBydeptNo(department.getOrgDeptNo());
            Users admin = usersService.findUserByName("admin", request);
            for (OrgDepartment d : list) {
                List<Users> l = usersService.getUsersByOrgDeptId(d.getOrgDeptId());
                if (l.size() > 0) {
                    json.setFlag(1);
                    json.setMsg(Constant.deleteMessage);
                    return json;
                }
                for (Users u : l){
                    if (u.getUserId().equals(admin.getUserId())){
                        json.setFlag(1);
                        json.setMsg(Constant.deleteMessage);
                        return json;
                    }
                }
            }
            for (OrgDepartment d : list) {
                orgDepartmentMapper.deleteByPrimaryKey(d.getOrgDeptId());
            }
            json.setFlag(0);
            json.setMsg("true");
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
            json.setMsg("false");
        }
        return json;
    }

    public ToJson getPartyList() {
        ToJson toJson = new ToJson(0, "成功");
        List<OrgDepartment> orgDeptData = orgDepartmentMapper.getAllOrgDept();
        toJson.setObj(orgDeptData);
        return toJson;
    }

    public ToJson getPartyDeptById(HttpServletRequest request,Integer orgDeptId) {
        ToJson toJson = new ToJson(1, "err");
        OrgDepartmentWithBLOBs orgDepartmentWithBLOBs = orgDepartmentMapper.selectByPrimaryKeyById(orgDeptId);
        List<Attachment> attachmentList=new ArrayList<Attachment>();
        if (orgDepartmentWithBLOBs != null) {
            orgDepartmentWithBLOBs.setOrgDeptParentName(orgDepartmentMapper.getDeptNameByDeptId(orgDepartmentWithBLOBs.getOrgDeptParent()));
            orgDepartmentWithBLOBs.setCountUser(orgPartyMemberMapper.countOrgParty(orgDepartmentWithBLOBs.getOrgDeptId()));
            if (orgDepartmentWithBLOBs.getAttachmentId() != null && orgDepartmentWithBLOBs.getAttachmentName() != null) {
                attachmentList= GetAttachmentListUtil.returnAttachment( orgDepartmentWithBLOBs.getAttachmentName(),orgDepartmentWithBLOBs.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.MODULE_photo);
            }

            orgDepartmentWithBLOBs.setAttachmentList(attachmentList);
            toJson.setObject(orgDepartmentWithBLOBs);
            toJson.setMsg("查询成功");
            toJson.setFlag(0);
            return toJson;
        }
        toJson.setMsg("数据为空");
        return toJson;
    }

    public ToJson getChDept(Integer deptId) {
        ToJson toJson = new ToJson(1, "err");
        if(deptId!=null){
            List<OrgDepartmentWithBLOBs> orgDepartmentWithBLOBs = orgDepartmentMapper.queryByDepIdList(deptId);
            if(orgDepartmentWithBLOBs.size()!=0){
                for (OrgDepartmentWithBLOBs departmentWithBLOBs : orgDepartmentWithBLOBs) {
                    departmentWithBLOBs.setDeptId(String.valueOf(departmentWithBLOBs.getOrgDeptId()));
                    departmentWithBLOBs.setDeptName(departmentWithBLOBs.getOrgDeptName());
                }
                toJson.setObj(orgDepartmentWithBLOBs);
                toJson.setMsg("查询成功");
                toJson.setFlag(0);
                return toJson;
            }
        }
        toJson.setMsg("数据为空");
        return toJson;
    }

    public ToJson delDepById(Integer deptId) {
        ToJson toJson = new ToJson(1, "err");
        try{
            if(deptId == null){
                toJson.setMsg("参数错误");
                return toJson;
            }
            int i = orgDepartmentMapper.selectChileById(deptId);
            if(i>0){
                toJson.setMsg("该支部有子支部,无法删除");
                return toJson;
            }
            int j = orgPartyMemberMapper.selectByDeptId(deptId);
            if(j>0){
                toJson.setMsg("该支部有所属党员,无法删除");
                return toJson;
            }
            int k = orgDepartmentMapper.deleteByPrimaryKey(deptId);
            if(k>0){
                toJson.setMsg("删除成功");
                toJson.setFlag(0);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return toJson;
    }
}